#ifndef STARTPROCESS_H
#define STARTPROCESS_H

#include <boost/process.hpp>
#include <iostream>
#include <vector>
#include <thread>
#include <queue>
#include <memory>
#include <mutex>

namespace bp = boost::process;

class StartProcess
{
public:
    StartProcess() = default;

    static void start_process(const std::string& program, const std::vector<std::string>& args) {
        try {
            bp::child c(program, bp::args(args));

            c.wait();

            if (c.exit_code() == 0) {
                std::cout << "Process completed successfully." << std::endl;
            } else {
                std::cerr << "Process failed with exit code: " << c.exit_code() << std::endl;
            }
        } catch (const std::exception& e) {
            std::cerr << "Exception occurred: " << e.what() << std::endl;
        }
    }

    static void run_concurrent_processes(const std::vector<std::pair<std::string, std::vector<std::string>>>& programs, size_t max_concurrent) {
        std::mutex mtx;
        size_t index = 0;
        size_t active_processes = 0;
        std::vector<std::unique_ptr<std::thread>> threads; // 使用 unique_ptr 管理线程

        while (index < programs.size() || active_processes > 0) {
            // 启动新进程，确保并发数不超过 max_concurrent
            if (active_processes < max_concurrent && index < programs.size()) {
                auto program_info = programs[index];
                threads.push_back(std::make_unique<std::thread>(start_process, program_info.first, program_info.second));
                ++active_processes;
                ++index;
            }

            // 等待所有活跃进程完成
            for (auto it = threads.begin(); it != threads.end();) {
                if (it->get()->joinable()) {
                    it->get()->join();
                    --active_processes;
                }
                it = threads.erase(it); // 移除已经完成的线程
            }
        }
    }
};

#endif // STARTPROCESS_H
